package com.appbee.songs.client.ui;

import java.util.List;

import javax.inject.Inject;

import com.appbee.core.client.design.PageStyle;
import com.appbee.core.client.design.celltable.CellTableResources;
import com.appbee.core.client.listener.SimpleSelectionListener;
import com.appbee.core.client.ui.HtmlEditor;
import com.appbee.core.client.ui.IMessageView;
import com.appbee.core.client.ui.LabelIntegerbox;
import com.appbee.core.client.ui.LabelTextbox;
import com.appbee.core.client.ui.MessageView;
import com.appbee.gdata.youtube.client.cell.AddEntryListener;
import com.appbee.gdata.youtube.client.model.SimpleEntry;
import com.appbee.gdata.youtube.client.presenter.SearchPresenter;
import com.appbee.gdata.youtube.client.search.Entry;
import com.appbee.gdata.youtube.client.ui.EmbeddedPlayer;
import com.appbee.lyrdb.shared.LyrSongProxy;
import com.appbee.songs.client.presenter.SongEditActivity;
import com.appbee.songs.client.text.SongsStrings;
import com.appbee.songs.client.ui.entry.EntryListView;
import com.appbee.songs.shared.SongProxy;
import com.appbee.yahoo.query.client.model.Album;
import com.appbee.yahoo.query.client.model.Track;
import com.appbee.yahoo.query.client.text.TrackStrings;
import com.appbee.yahoo.query.client.ui.TrackTable;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.HasEditorErrors;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.web.bindery.requestfactory.gwt.client.RequestFactoryEditorDriver;
import com.google.web.bindery.requestfactory.shared.RequestFactory;

public class SongEditView extends Composite implements SongEditActivity.View,
		Editor<SongProxy>, HasEditorErrors<SongProxy>, AddEntryListener,SearchPresenter.ListView
{

	private static SongsEditViewUiBinder uiBinder = GWT
			.create(SongsEditViewUiBinder.class);

	interface SongsEditViewUiBinder extends UiBinder<Widget, SongEditView>
	{
	}

	interface Driver extends
			RequestFactoryEditorDriver<SongProxy, SongEditView>
	{
	}

	@UiField(provided = true)
	PageStyle pageStyle;

	@UiField(provided = true)
	MessageView messageView;

	@UiField
	Button cancelButton;
	@UiField
	Button saveButton;

	@UiField
	LabelIntegerbox number;
	@UiField
	LabelTextbox name;
	@UiField
	@Ignore
	Label resultInfo;
	@UiField
	LabelTextbox artist;
	@UiField
	LabelTextbox album;
	@UiField
	LabelTextbox releaseYear;
	@UiField
	LabelTextbox genre;
	@UiField
	LabelTextbox keyTone;
	@UiField
	LabelTextbox startingPlayer;
	@UiField(provided = true)
	HtmlEditor lyrics;
	
	@UiField
	Button youtubeSearchButton;
	
	@UiField
	Button lyricsSearchButton;
	
	@UiField(provided=true)
	EntryListView youtubeData;
	
//	@UiField(provided=true)
//	CellList<Entry> feedList;

	@UiField
	EmbeddedPlayer player;
	private SongEditActivity presenter;
	
	private final TrackTable trackTable;
	private final PopupPanel trackPopupPanel;

	private final YoutubeSearchPopup youtubeSearchPopup;

	private final LyrSongSearchPopup lyrSongSearchPopup;

	@UiField(provided = true)
	SongsStrings songsStrings;

	@UiField(provided = true)
	ISongEditStyle editStyle;
	

	@Inject
	public SongEditView(PageStyle style,
						ISongEditStyle editStyle,
						SongsStrings songsStrings,
						TrackStrings trackStrings,
						MessageView messageView,
						EntryListView entryEditor,
						HtmlEditor lyrics,
						CellTableResources cellTableRes,
						final YoutubeSearchPopup youtubeSearchPopup,
						final LyrSongSearchPopup lyrSongSearchPopup)
	{
		this.pageStyle = style;
		this.editStyle = editStyle;
		this.songsStrings = songsStrings;
		this.youtubeData = entryEditor;
		this.messageView = messageView;
		this.lyrics = lyrics;
		this.youtubeSearchPopup = youtubeSearchPopup;
		this.lyrSongSearchPopup = lyrSongSearchPopup;
		
		//Track info
		trackTable = new TrackTable(10, cellTableRes, trackStrings);
		trackPopupPanel = new PopupPanel();
		trackPopupPanel.setAnimationEnabled(true);
		trackPopupPanel.setAutoHideEnabled(true);
		trackPopupPanel.setWidget(trackTable);
				

		youtubeSearchPopup.setEntryListener(this);

		initWidget(uiBinder.createAndBindUi(this));

		saveButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				presenter.onSave();

			}
		});

		cancelButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				presenter.onCancelClick();
			}
		});
		
		youtubeSearchButton.addClickHandler(new ClickHandler()
		{
			
			@Override
			public void onClick(ClickEvent event)
			{
				youtubeSearchPopup.showRelativeTo(youtubeSearchButton);
			}
		});

		youtubeSearchPopup.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
		{

			@Override
			public void onSelectionChange(SelectionChangeEvent event)
			{
				Entry entry = youtubeSearchPopup.getSelectedTrack();
				player.setEntry(entry);
			}
		});
		
		youtubeData
				.setSelectionListener(new SimpleSelectionListener<SimpleEntry>()
		{
			
			@Override
					public void onSelected(SimpleEntry entry)
			{
				player.setSimpleEntry(entry);
			}
		});

		lyricsSearchButton.addClickHandler(new ClickHandler()
		{
			
			@Override
			public void onClick(ClickEvent event)
			{
				lyrSongSearchPopup.showRelativeTo(lyricsSearchButton);
			}
		});
		
		lyrSongSearchPopup.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
		{
			
			@Override
			public void onSelectionChange(SelectionChangeEvent event)
			{
				presenter.onLyricSelection(lyrSongSearchPopup.getSelectedSong());
			}
		});
		

		name.addKeyDownHandler(new KeyDownHandler()
		{
			
			@Override
			public void onKeyDown(KeyDownEvent event)
			{
				if(event.getNativeKeyCode()==KeyCodes.KEY_ENTER)
				{
					presenter.onSearchByTrack();
				}
			}
		});
		
		trackTable.addSelectListener(new SelectionChangeEvent.Handler()
		{
			
			@Override
			public void onSelectionChange(SelectionChangeEvent event)
			{
				Track track = trackTable.getSelectedTrack();
				if(track.getArtist()!=null)
					artist.setValue(track.getArtist().getName());
				if(track.getCategory()!=null)
					genre.setValue(track.getCategory().getName());
				Album trackAlbum = track.getAlbum();
				if(trackAlbum!=null && trackAlbum.getRelease()!=null)
					album.setValue(trackAlbum.getRelease().getTitle());
				releaseYear.setValue(track.getReleaseYear());
				
				trackPopupPanel.hide();
				presenter.onTrackSelected(track);
			}
		});
		
	}

	@Override
	public RequestFactoryEditorDriver<SongProxy, ?> createDriver(EventBus eventBus, RequestFactory rf)
	{
		Driver driver = GWT.create(Driver.class);
		driver.initialize(eventBus, rf, this);
		return driver;
	}


	@Override
	public IMessageView getMessageView()
	{
		return messageView;
	}

	@Override
	public void setPresenter(SongEditActivity presenter)
	{
		this.presenter = presenter;

	}

	@Override
	public void showErrors(List<EditorError> errors)
	{
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		boolean hasError = false;
		for (EditorError editorError : errors)
		{
			if(editorError.isConsumed())
			{
				sb.append(SafeHtmlUtils.fromString(editorError.getMessage()));
				sb.appendHtmlConstant("<br>");
				editorError.setConsumed(true);
				hasError = true;
			}
		}
		if(hasError)
			messageView.showError(sb.toSafeHtml());
		else
			messageView.clearMessage();

	}

	@Override
	public void onAdd(Entry entry)
	{
		youtubeData.add(entry);
	}

	@Override
	public void showEntryList(List<Entry> list)
	{
	}

	@Override
	public void clearEntryList()
	{
	}

	@Override
	public String getNameValue()
	{
		return name.getValue();
	}

	@Override
	public void setTrackData(List<Track> list)
	{
		trackTable.setRowData(list);
		trackPopupPanel.showRelativeTo(name);
		trackTable.focus();
	}

	@Override
	public void showLyricList(List<LyrSongProxy> response)
	{
	}

	@Override
	public void setLyrics(String response)
	{
		lyrics.setValue(response);
	}

	@Override
	public void addEntry(Entry entry)
	{
		youtubeData.add(entry);
	}

	@Override
	public void clearEntrys()
	{
		youtubeData.clear();
	}

	@Override
	public void selectFirstEntry()
	{
		youtubeData.selectFirstEntry();
	}

	@Override
	public void clearTubeSearchList()
	{
		youtubeSearchPopup.clearData();
	}

	@Override
	public void clearPlayer()
	{
		player.setSrc(null);
	}

	@Override
	public void clearTextSearchList()
	{
		lyrSongSearchPopup.clearData();
	}

	@Override
	public void setNumberValue(Integer value)
	{
		number.setValue(value);
	}

}
